package com.waves.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.waves.core.utils.StringUtils;
import com.waves.pay.dao.OrderDao;
import com.waves.pay.domain.entity.Orders;
import com.waves.pay.service.OrderService;
import com.waves.task.dao.TaskReceiveDao;
import com.waves.task.domain.entity.Task;
import com.waves.task.domain.entity.TaskReceive;
import com.waves.task.domain.enums.TaskReceiveStatusEnum;
import com.waves.task.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝回调服务接口
 */
@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/alipay/")
public class AliPayController {

    public static final String TRADE_SUCCESS = "TRADE_SUCCESS";
    public static final int STATUS_CODE = 0;
    @Value("${alipay.alipay_public_key}")
    private String alipayPublicKey;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderDao orderDao;

    @Resource
    private TaskService taskService;

    @Resource
    private TaskReceiveDao taskReceiveDao;


    /**
     * 回调地址：http://ip地址/demand/alipay/alipay_notify_url
     */
    @RequestMapping(value = "alipay_notify_url", method = RequestMethod.POST)
    @Transactional
    public String payNotify(HttpServletRequest request) throws AlipayApiException {
        String tradeStatus = request.getParameter("trade_status");
        log.info("支付回调，消息接收 {}", tradeStatus);
        if (!tradeStatus.equals(TRADE_SUCCESS)) {
            log.error("支付失败，消息回调{}", tradeStatus);
            return "false";
        }

        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }

        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayPublicKey, "UTF-8"); // 验证签名
        // 支付宝验签
        if (!checkSignature) {
            return "false";
        }
        // 修改订单
        Orders order = orderDao.get(params.get("out_trade_no"));
        String gmtPayment = params.get("gmt_payment");
        order.setBuyerId(params.get("buyer_id"))
                .setGmtPayment(gmtPayment)
                .setBuyerPayAmount(params.get("buyer_pay_amount"))
                .setTradeNo(params.get("trade_no"))
                .setTradeStatus(params.get("trade_status"))
                .setStatus(1L);
        orderService.updateById(order);

        // receiveId不为空 说明是求助贴 领取人主动支付
        if (order.getReceiveId() != null) {
            TaskReceive taskReceive = taskReceiveDao.getById(order.getReceiveId());
            taskReceive.setStatus(1);
            taskReceiveDao.updateById(taskReceive);
        } else {
            // receiveId为空,说明是赏金贴和征召贴，修改任务状态
            Task task = taskService.getBaseMapper().selectById(order.getTaskId());
            task.setStatus(TaskReceiveStatusEnum.RECEIVE_STATUS_ING.getType());
            taskService.updateById(task);
        }

        // 验签通过
        log.info("支付回调，交易名称: {}", params.get("subject"));
        log.info("支付回调，交易状态: {}", params.get("trade_status"));
        log.info("支付回调，支付宝交易凭证号: {}", params.get("trade_no"));
        log.info("支付回调，商户订单号: {}", params.get("out_trade_no"));
        log.info("支付回调，交易金额: {}", params.get("total_amount"));
        log.info("支付回调，买家在支付宝唯一id: {}", params.get("buyer_id"));
        log.info("支付回调，买家付款时间: {}", gmtPayment);
        log.info("支付回调，买家付款金额: {}", params.get("buyer_pay_amount"));
        log.info("支付回调，支付回调，更新订单 {}", params.get("out_trade_no"));
        return "success";
    }

}
